/**
 * Created by Loriling on 2015/6/1.
 */
define(["js/softphone/calltype", "js/softphone/workinfo", "js/softphone/pdstype", "js/objective" + $E.jsv], function (CallType, WorkInfo, PDSType, Objective) {
    var PAGE_ID = "EXTNAT";
    var PROPERTY_SUMMARY = "TEMP.SUMMARY";
    var PROPERTY_SUMMARY_COMMENTS = "TEMP.SUMMARY_COMMENTS";
    var PROPERTY_SUMMARY_TYPE = "TEMP.SUMMARY_TYPE";
    var PROPERTY_HANDLE_BY = "TEMP.HANDLE_BY";
    var PROPERTY_HANDLE_GROUP = "TEMP.HANDLE_GROUP";
    var PROPERTY_EXPECT_STARTTIME = "TEMP.EXPECT_STARTTIME";
    var PROPERTY_OBJECTIVE_TYPE = "TEMP.OBJECTIVE_TYPE";
    var PROPERTY_CALLNATURE_TREE = "TEMP.CALLNATURE_TREE";
    var SUMMARY_TYPE_NORMAL = 0;
    var SUMMARY_TYPE_REPLY = 1;
    var SUMMARY_TYPE_APCALL = 2;

    var updateEvent = function (proj, eventGuid, customerGuid, callType, obStatus, eventComment, objectiveStatus) {
        var nowDateStr = $F.getDbTime();
        var softCommonCall = "customer_guid=" + customerGuid + "|contact_customer_guid=" + proj.getCurrentContactCustomerGuid() +
            "|customername=" + proj.customer.getValue("customername") + "|HandleBy_ID=" +
            $E.staff.id + "|HandleGroup_ID=" + proj.groupId + "|WorkStartTime=" + proj.cwInfo.workStartTime +
            "|WorkEndTime=" + nowDateStr + "|EVENT_GUID=" + eventGuid + "|comments=" + (eventComment || '');
        if (!$F.isEmpty(obStatus)) {
            softCommonCall += "|CallResult_ID=" + obStatus;
        }
        if (callType == CallType.OUTBOUND) {
            softCommonCall += "|calltype=2";
            if (!objectiveStatus) {
                var objective = proj.obUtil.queryObjectiveByGuid(proj.outbound.obInfo.currentOBObjectiveGuid);
                if (objective) {
                    objectiveStatus = objective[2];
                }
            }
            if (objectiveStatus) {
                softCommonCall += "|OBJECTIVESTATUS=" + objectiveStatus;
            }
        } else if (callType == CallType.INBOUND) {
            softCommonCall += "|calltype=1";
        } else if (callType == CallType.PDS_OUTBOUND) {
            softCommonCall += "|calltype=6";
        }
        $E.softphone.simpleCommonCall("setevent", softCommonCall);
        $F.log("CallSummary", "Event update with:" + softCommonCall);
    }

    var CallSummary = function (proj) {
        this.project = proj;
        this.instance;
        this.initialized = false;

        var obUtil = proj.obUtil;

        //根据界面选择，保存或者更新objective oblist eventobjective eventcallnature
        var handleSummary = function (eventGuid, customerGuid, obStatus, instance) {
            if (!instance) {
                return 1;
            }
            var cwInfo = proj.cwInfo;
            var eventGuid = cwInfo.eventGuid;
            var handleById;
            var handleGroupId;
            var comments = instance.getValue(PROPERTY_SUMMARY_COMMENTS) || '';
            var summaryType = instance.getValue(PROPERTY_SUMMARY_TYPE);
            if (summaryType == SUMMARY_TYPE_REPLY || summaryType == SUMMARY_TYPE_APCALL) {
                handleById = instance.getValue(PROPERTY_HANDLE_BY);
                handleGroupId = instance.getValue(PROPERTY_HANDLE_GROUP);
            }
            var nowDateStr = $F.getDbTime();
            var expectStartTime = instance.getValue(PROPERTY_EXPECT_STARTTIME);
            //start to handle
            if (summaryType == SUMMARY_TYPE_NORMAL) {

            } else if (summaryType == SUMMARY_TYPE_REPLY || summaryType == SUMMARY_TYPE_APCALL) {
                var otId = instance.getValue(PROPERTY_OBJECTIVE_TYPE);
                if ($F.isEmpty(otId)) {
                    $F.alert($F.lang('callSummary.obtypeRequired'));
                    return -1;
                }

                var extTBName = "";
                var objective = new BoundData("objective" + $E.staff.epidSql + (extTBName || ''));
                objective.KeyInfoEdit("OBJECTIVE_GUID");
                objective.setCreateInfo("CREATEDDATE", "CREATEDBY", $E.staff.id);
                objective.setModifyInfo("MODIFIEDDATE", "MODIFIEDBY", $E.staff.id);
                objective.NewValueEdit("OBJECTIVETYPE_ID", otId);
                objective.NewValueEdit("OBJECTIVESTATUS", "OPEN");
                objective.NewValueEdit("COMMENTS", comments);

                var obList = new BoundData("oblist" + $E.staff.epidSql + (extTBName || ''));
                obList.KeyInfoEdit("OBLIST_GUID");
                obList.setCreateInfo("CREATEDDATE", "CREATEDBY", $E.staff.id);
                obList.setModifyInfo("MODIFIEDDATE", "MODIFIEDBY", $E.staff.id);
                obList.NewValueEdit("ExpectStartTime", expectStartTime, $CONST.BoundType.F_Date);
                obList.NewValueEdit("OBStatus", obStatus);
                obList.NewValueEdit("HandleBy_ID", handleById);
                obList.NewValueEdit("HandleGroup_ID", handleGroupId);


                var ret = proj.commonQuerySync("CallSummary.Objective.queryByTypeAndCustomer", [$E.staff.epidSql, customerGuid, otId]);

                if (!$F.isNull(ret) && ret.value[0].count > 0) {
                    $F.log("CallSummary.handleSummary", "Objective found by customer_guid:" + customerGuid + ". So update objective");
                    var oId = ret.value[0].fields[0][0];
                    objective.NewValueEdit("OBJECTIVE_GUID", oId);
                    objective.NewValueEdit("OBHandleGroup", $E.staff.id);
                    objective.NewValueEdit("OBHandleBy", proj.groupId);

                    ret = proj.commonQuerySync("CallSummary.OBList.queryByOId", [$E.staff.epidSql, oId]);

                    if (!$F.isNull(ret) && ret.value[0].count > 0) {
                        var obListGuid = ret.value[0].fields[0][0];
                        obList.NewValueEdit("OBLIST_GUID", obListGuid);
                    } else {
                        obList.NewValueEdit("OBLIST_GUID", Guid.raw());
                        obList.NewValueEdit("Objective_GUID", oId);
                        obList.NewValueEdit("ObjectiveType_ID", otId);
                        obList.NewValueEdit("Max_Attempt", "3", $CONST.BoundType.F_Int);
                    }

                    var APCALL = proj.getParam("APCALL");
                    if (APCALL == "1") {
                        if (!$F.isEmpty(obStatus)) {
                            obStatus = obStatus.trim();
                            if ($F.equalsIgnoreCase(obStatus, "APCALL") || $F.equalsIgnoreCase(obStatus, "REPLY")) {
                                if (!$F.isEmpty(handleById)) {
                                    obUtil.updateOblistAppCall(obList);
                                }
                            }
                        }
                    }

                } else {
                    $F.log("CallSummary.handleSummary", "Objective not found by customer_guid:" + customerGuid + " and objectiveType:" + otId + ". So no oblist been created");

                    objective.NewValueEdit("OBJECTIVE_GUID", Guid.raw());
                    objective.NewValueEdit("HandleBy_ID", $E.staff.id);
                    objective.NewValueEdit("HandleGroup_ID", proj.groupId);
                    objective.NewValueEdit("Customer_GUID", customerGuid);
                    objective.NewValueEdit("FirstContactDate", nowDateStr, $CONST.BoundType.F_Date);
                    objective.NewValueEdit("LastContactDate", nowDateStr, $CONST.BoundType.F_Date);
                    objective.NewValueEdit("IsContact", "1");
                    objective.NewValueEdit("TryTimes", "1", $CONST.BoundType.F_Int);
                    objective.NewValueEdit("Event_GUID", eventGuid);

                    obList.NewValueEdit("OBLIST_GUID", Guid.raw());
                    obList.NewValueEdit("Objective_GUID", objective.getValue("OBJECTIVE_GUID"));
                    obList.NewValueEdit("ObjectiveType_ID", otId);
                    obList.NewValueEdit("Max_Attempt", "3", $CONST.BoundType.F_Int);

                    var eventObjective = new BoundData("EventObjective" + $E.staff.epidSql + (this.extTBName || ''));
                    eventObjective.NotFindDupli = 1;
                    eventObjective.KeyInfoEdit("OBJECTIVE_GUID");
                    eventObjective.NewValueEdit("EVENT_GUID", eventGuid);
                    eventObjective.NewValueEdit("OBJECTIVE_GUID", objective.getValue("OBJECTIVE_GUID"));
                    eventObjective.NewValueEdit("ObjectiveType_ID", otId);
                    eventObjective.NewValueEdit("ObjectiveStatus", objective.getValue("ObjectiveStatus"));
                    eventObjective.NewValueEdit("workstarttime", proj.cwInfo.workStartTime, $CONST.BoundType.F_Date);

                    objective.SubTableAdd("eventObjective", eventObjective);
                }
                objective.SubTableAdd("obList", obList);

                var exec = 0;
                $F.log('CallSummary.handleSummary', 'Start save objective and obList');

                var mRs = $F.ajaxSync("SystemDo5", {
                    token: proj.token,
                    dbPool: '',
                    xml: objective.getData()
                }, proj.digest);

                $F.log('CallSummary.handleSummary', 'Save objective and oblist result : ' + mRs);
            }
//            insertCallNature();
            instance.doCmd("P-100");
            return 1;
        };

        this.doAfterCallSummaryEnd = function (callType, nextShow) {
            var ob = this.project.outbound;
            if (callType == CallType.OUTBOUND) {
                $F.log("CallSummary.doAfterCallSummaryEnd", "Do after outbound call summary.");
                var obInstance = proj.getModuleInstance($CONST.ModuleName.ADDIN_OUTBOUND);

                if (ob.obInfo.autoNext) {
                    var oblistGuid, customerNotifyGuid;
                    oblistGuid = obUtil.getConfigedAPCall(proj);
                    if (!$F.isEmpty(oblistGuid)) {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Find oblist:" + oblistGuid + " with configed apcall sql.");
                    } else {
                        var LOGOBJ = proj.getParam("LOGOBJ");
                        if (LOGOBJ == "1") {
                            if (ob.obInfo.objectiveTypeOblistType == 0) {
                                oblistGuid = obUtil.getOBList();
                            } else if (ob.obInfo.objectiveTypeOblistType == 1) {
                                oblistGuid = obUtil.getAPCallOBList();
                            } else if (ob.obInfo.objectiveTypeOblistType == 2) {
                                oblistGuid = obUtil.getGroupOBList();
                            } else if (ob.obInfo.objectiveTypeOblistType == 3) {
                                oblistGuid = obUtil.getPersonalOBList();
                            }
                        } else {
//                            if(obInstance.hasRolling($CONST.Rolling.OBLIST)){
//                                var obl = obInstance.getRolling($CONST.Rolling.OBLIST);
//                                if(!$F.isNull(obl)){
//                                    oblistGuid = obl.oblist_guid;
//                                    customerNotifyGuid = obl.customernotify_guid;
//                                }
//                            }
                        }
                    }

                    if (!$F.isEmpty(oblistGuid)) {
                        $F.fireValue(obInstance, "TEMP.NEXT_OBLIST_GUID", oblistGuid);
                        proj.tabReopen(obInstance);
                        $F.log("CallSummary.doAfterCallSummaryEnd", "OutBound module book next oblist, and do outbound. OBList_guid is " + oblistGuid);
                        return;
                    } else {
                        $F.alert($F.lang('callSummary.noNextOB'));
                        ob.obInfo.autoNext = false;
                        $F.log("CallSummary.doAfterCallSummaryEnd", "OutBound module book next oblist, but no oblist left.");
                    }
                } else {
                    $F.log("CallSummary.doAfterCallSummaryEnd", "Do after auto call summary without autoNextOB.");
                }
                try {
                    if (nextShow) {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page after call summary with dyn page param nextShow:" + nextShow);
                        this.openNextPageAfterAutoSummary(nextShow);
                    } else if (ob.obInfo.onlyReturn) {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Find only return parameter when do call summary.");
                        //openOBListStackForOnlyReturn();
                        return;
                    } else if (ob.obInfo.callback) {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Call back call.");
                        return;
                    } else {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page when do endSummary btn click with outbound");
                        var OBNEPE = proj.getParam("OBNEPE");
                        if (!$F.isEmpty(OBNEPE)) {
                            $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page after call summary with OBNEPE:" + OBNEPE);
                            this.openNextPageAfterAutoSummary(OBNEPE);
                        } else {
                            $F.log("CallSummary.doAfterCallSummaryEnd", "OBNEPE is null, no special page will be opened.");
                        }
                    }
                } catch (e) {
                    $F.err("CallSummary.doAfterCallSummaryEnd", "Error occurred when do after call summary:" + e.message);
                }
            } else {
                $F.log("CallSummary.doAfterCallSummaryEnd", "Do after call summary, calltype is " + callType);
                try {
                    if (nextShow) {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page after call summary with dyn page param nextShow:" + nextShow);
                        this.openNextPageAfterAutoSummary(nextShow);
                    } else {
                        $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page when do endSummary btn click with calltype " + callType);
                        if (callType == CallType.INBOUND) {
                            var IBNEPE = proj.getParam("IBNEPE");
                            if (!$F.isEmpty(IBNEPE)) {
                                $F.log("CallSummary.doAfterCallSummaryEnd", "Open next page after call summary with IBNEPE:" + IBNEPE);
                                this.openNextPageAfterAutoSummary(IBNEPE);
                            } else {
                                $F.log("CallSummary.doAfterCallSummaryEnd", "IBNEPE is null, no special page will be opened.");
                            }
                        }
                    }
                } catch (e) {
                    $F.err("CallSummary.doAfterCallSummaryEnd", "Error occurred when do after call summary:" + e.message);
                }
            }
        };

        this.openNextPageAfterAutoSummary = function (nextShow) {
            if (nextShow.indexOf("$") == 0) {
                nextShow = nextShow.substr(1).toUpperCase();
                $F.log("CallSummary.openNextPageAfterAutoSummary", "Open module " + nextShow + " after call summary.");
                switch (nextShow) {
                    case "TEL":
                        proj.events.notify($CONST.WorkLoadNotifyEvent.OB);
                        break;
                    case "JOBLIST":
                        proj.events.notify($CONST.WorkLoadNotifyEvent.WO);
                        break;
                }
            } else {
                var menu = proj.findMenuById(nextShow);
                if (menu) {
                    $F.log("CallSummary.openNextPageAfterAutoSummary", "Open menu " + nextShow + " after auto call summary.");
                    proj.onMenu(menu);
                } else {
                    $F.log("CallSummary.openNextPageAfterAutoSummary", "Try to open menu " + nextShow + " after auto call summary, but not found.");
                }
            }
        };


        this.doSummary = function (nextShow, customerGuid, objectiveStatus, eventComments) {
            var instance = this.instance;
            var proj = this.project;
            var cwInfo = proj.cwInfo;
            var eventGuid = cwInfo.eventGuid;
            var specCust = false;
            if (customerGuid)
                specCust = true;
            customerGuid = customerGuid || proj.getCurrentCalledCustomerGuid();
            var callType = cwInfo.callType;

            if ($F.isEmpty(customerGuid)) {
                $F.log("CallSummary.doSummary", "Not found current customer.");
                $F.alert($F.lang('callSummary.noCurrentCustomer'));
                proj.events.notify($CONST.ModuleEvent.ECM_WORKEND);
                if (instance) {
                    proj.tabClose(instance.id);
                }
                return;
            }
            var obStatus = "CLOSE";


            if (instance) {
                eventComments = instance.getValue(PROPERTY_SUMMARY_COMMENTS);
                //CLOSE  REPLY  APCALL
                var summaryType = instance.getValue(PROPERTY_SUMMARY_TYPE);
                if (summaryType == "1") {
                    obStatus = "REPLY";
                } else if (summaryType == "2") {
                    obStatus = "APCALL";
                }
            }


            if (!$F.isEmpty(eventGuid)) {
                updateEvent(proj, eventGuid, customerGuid, callType, obStatus, eventComments, objectiveStatus);
                if (cwInfo.workStatus == WorkInfo.WT_PDS_OB) {
                    if (cwInfo.pdsType == PDSType.ASPECT_PDS) {
                        //handleAspectPDSSummary();
                    } else if (cwInfo.pdsType == PDSType.AVAYA_PDS) {
                        //handleAvayaPDSSummay();
                    } else {
                        //handlePDSSummary();
                    }
                } else {
                    //根据界面选择，保存或者更新objective oblist eventobjective eventcallnature
                    var ret = handleSummary(eventGuid, customerGuid, obStatus, instance);
                    if (ret == -1) {
                        return;
                    }
                }
            } else {
                $F.log("CallSummary.doSummary", "Not found event_guid from ECore.");
            }

            if (!customerGuid) {
                $F.log("CallSummary.doSummary", "Call saveCurrentCustomer");
                proj.customer.autoSaveCustomer();
            }

            this.callSummaryEnd(customerGuid, specCust);
            proj.events.notify($CONST.ModuleEvent.ECM_WORKEND);
            //control what to do or which page to open when summary end.
            if (proj.cwInfo.callBack) {
                proj.cwInfo.callBack = false;
                $F.log("CallSummary.doSummary", "Set callInfo callback false, end Summary callback call.");
            } else {
                this.doAfterCallSummaryEnd(callType, nextShow);
            }
        };


        //close all other tabs and remain the customer tab and clear current customer
        this.callSummaryEnd = function (customerGuid, specCust) {
            var proj = this.project;
            if (!specCust) {// 如果不是指定customer（也就是说是框架客户）则清空当前客户
                proj.clearCustomer();
            }
            // proj.tabCloseAllStateful(customerGuid);//关闭所有和这个客户相关的有状态动态页面
        }
    };

    CallSummary.prototype = {
        init: function () {
            var cs = this;
            var proj = this.project;
            $F.log("CallSummary - init", "Init CallSummary.");
            proj.events.register($CONST.ModuleEvent.ECM_CALLSUMMARY, $CONST.ModuleName.ADDIN_CALLSUMMARY, function (parameters) {
                $F.log("CallSummary", "Receive auto call summary message.");
                if (proj.workDuration) {
                    var nextShow, customerGuid, objectiveStatus, eventComments;
                    if (parameters) {
                        var showModule = parameters.showModule == 1;
                        if (showModule) {
                            $F.log("CallSummary", "Show CallSummary module when receive the auto summary message.");
                            cs.open();
                        }
                        nextShow = parameters.nextShow;
                        customerGuid = parameters.customerGuid;
                        objectiveStatus = parameters.objectiveStatus;
                        eventComments = parameters.eventComments;
                    }
                    if (proj.cwInfo.workStatus == WorkInfo.WT_PDS_OB) {
                        $F.log("CallSummary", "Do auto call summary in pds enviroment.");
                    } else {
                        $F.log("CallSummary", "Do auto call summary.");
                    }
                    cs.doSummary(nextShow, customerGuid, objectiveStatus, eventComments);
                } else {
                    $F.log("CallSummary", "Not in work duration, hence not do anything.");
                    //jeff said that need call this whether in work duration or no
                    $E.softphone.notifyWorkEnd();
                }
            });
            proj.events.register($CONST.ModuleEvent.EXTERNAL_MESSAGE, $CONST.ModuleName.ADDIN_CALLSUMMARY, function (parameters) {
                $F.log("CallSummary", "Receive EXTERNAL_MESSAGE.");
                var externalMsgType = parameters.type;
                if (externalMsgType === "setCallNature") {
                    if (cs.instance) {
                        var callNatureId = parameters.callNatureId;
                        if (callNatureId) {
                            $F.log("CallSummary", "setCallNature " + callNatureId);
                            var callNatureTree = cs.instance.getValue(PROPERTY_CALLNATURE_TREE);
                            if ($F.isEmpty(callNatureTree)) {
                                callNatureTree = callNatureId;
                            } else {
                                callNatureTree = callNatureTree + "," + callNatureId;
                            }
                            $F.fireValue(cs.instance, PROPERTY_CALLNATURE_TREE, callNatureTree);
                        }
                    }
                }
            });

            var sbcasu = proj.getParam(PAGE_ID);
            if (!sbcasu) {
                $F.log('CallSummary - init', 'No sysc_parameter [' + PAGE_ID + '] defined.');
                return false;
            }
            var instance = $D.createInstance(proj, sbcasu, '', '', undefined, true, 'DYN', proj.veSupport);
            if (!instance) {
                $F.log('CallSummary - init', 'Create CallSummary instance failed: ' + sbcasu);
                return false;
            }
            cs.instance = instance;

            instance.propertyListener($CONST.ModuleName.ADDIN_CALLSUMMARY, function (pName, pValue) {
                pName = pName.toUpperCase();
                if (pName === PROPERTY_SUMMARY) {
                    if (pValue === "1") {
                        cs.doSummary();
                        $F.fireValue(instance, PROPERTY_SUMMARY, "0");
                    }
                }
            });
            proj.addModuleInstance($CONST.ModuleName.ADDIN_CALLSUMMARY, instance);
            this.initialized = true;
        },
        open: function () {
            if (!this.initialized) {
                $F.alert($F.lang('callSummary.noInitialized'));
                return false;
            }
            var cs = this;
            var proj = this.project;
            //查看是否开启着小结tab
            //检查缓存中是否有小结instance
            var nav = proj.getNavs();
            for (var i = 0; i < nav.length; i++) {
                if ($(nav[i]).data("addinId") === $CONST.ModuleName.ADDIN_CALLSUMMARY) {
                    proj.tabReopenByIndex(i);
                    cs.instance.doCmd("P-55");
                    return true;
                }
            }
            //没有发现小结tab，则创建一个
            var tab = proj.tabCreate('CallSummary', $F.lang('callSummary.callSummary'), true, true);
            tab.data("instance", cs.instance);
            tab.data("addinId", $CONST.ModuleName.ADDIN_CALLSUMMARY);
            $D.live(cs.instance, tab.data("container"));
            cs.instance.doCmd("P-55");
            return true;
        }
    };

    var csInst = {};
    return {
        getInstance: function (proj) {
            if (!csInst[proj.id]) {
                csInst[proj.id] = new CallSummary(proj);
            }
            return csInst[proj.id];
        }
    };
});
